<template>
  <el-dialog
    class="assign-role"
    title="分配角色"
    :visible="showRoleDialog"
    @close="handleCloseDialog"
    @open="handleOpen"
  >
    <!-- 这里准备复选框 -->
    <!-- label一般是给用户看的,value是交给后台的
    多选框有点特殊,label 是用于提交给后台的,展示给用户看的提示文字直接用插槽提供 -->
    <el-checkbox-group v-model="checkList" v-loading="loading">
      <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">
        {{ item.name }}
      </el-checkbox>

    </el-checkbox-group>

    <template #footer>
      <el-button type="primary" size="small" @click="clickAssignRoles">确定</el-button>
      <el-button size="small" @click="handleCloseDialog">取消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { reqGetROleList } from '@/api/setting'
import { reqGetBaseInfo } from '@/api/user'
import { reqAssignRoles } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      // 这个数据不仅可以收集用户选择的项,还可以控制一开始默认选中哪几个!!!!!
      checkList: [],
      roleList: [],
      loading: false
    }
  },
  created() {

  },
  methods: {
    handleCloseDialog() {
      this.$emit('update:showRoleDialog', false)
      this.checkList = ''
    },
    handleOpen() {
      this.loading = true
      // 获取角色列表
      // this.GetROleList()
      // 获取用户之前的角色
      // this.getEmployeeDetail()
      // async函数的执行结果就是promise,默认封装了一层promise
      Promise.all([this.GetROleList(), this.getEmployeeDetail()]).then(() => {
        this.loading = false
      })
    },
    async GetROleList() {
      const { data: { rows }} = await reqGetROleList(1, 99999)
      // console.log(res)
      this.roleList = rows
    },
    async getEmployeeDetail() {
      const { data: { roleIds }} = await reqGetBaseInfo(this.userId)
      // console.log(res)
      this.checkList = roleIds
    },
    async clickAssignRoles() {
      await reqAssignRoles(this.userId, this.checkList)
      // console.log(res)
      this.$message.success('给用户分配角色成功')
      this.handleCloseDialog()
    }
  }
}
</script>
